Question 3 ( 20 points ).
The classes My_int and CUCSApplication are defined on the next page. Each object of class My_int encapsulates an integer value in a field named x, i.e., each My_int is an object version of an integer.
For example,
My_int p = new My_int( 3 );
System.out.println( p.x );
would print 3.
( a ) Complete the implementation of the My_int constructor and the method add.
( b ) Show the output of executing CUCSApplication.main in
the table below:
Output:
a= 20 b= 10
c= 30 d= 40
e= [60] f= [50]
true
e.x= 60 old_e.x= [60]
g + h= [150]
import java.io.*;
// My_int is a
class representing integers as objects.
class My_int
{
public int x;
// Construct a My_int object with integer
value x
My_int ( int x )
{
this.x = x;
}
static void swap2( My_int a,
My_int b )
{
int temp = a.x; a.x = b.x; b.x =
temp;
}
public String toString()
{
return
"[" + x + "]";
}
//a.add(b) returns the sum of a and b's
values as a My_int
public My_int add( My_int b )
{
return new
My_-Int( x + b.x );
}
}
class CUCSApplication
{
static void swap1( int a, int b )
{
int temp = a; a = b; b = temp;
} // swap1
public static void main( String[]
args )
{
// set a to 10, b to 20, "swap" a and b, and print a and b
int a = 10;
int b = 20;
int temp = a; a = b; b = temp;
System.out.println( "a=" + a + "
b=" + b );
// set c to 30, d to 40,
"swap" c and d, and print c and d.
int c = 30;
int d = 40;
swap1( c, d );
System.out.println( "c=" + c + "
d=" + d );
// set e to 50, f to 60,
"swap" e and f, and print e and f.
My_int e = new My_int( 50 );
My_int f = new
My_int( 60 );
My_int old_e = e;
My_int.swap2( e, f );
System.out.println( "e=" + e + "
f=" + f );
System.out.println( e ==
old_e );
System.out.println( "e.x= " + e.x + "
old_e.x= " + old_e );
// set g to 7, h to 80, "add"
g and h, and print their sum
My_int g = new My_int( 70 );
My_int h = new
My_int( 80 );
System.out.println( "g + h= " + g.add( h ) );
}
} //
CUCSApplication